<?php
namespace control;
/*
*驾驶员档案类
*/

class logisticsDriverClass extends adIndexClass
{
    private const page = 'logisticsDriver';
    private const table = 'logistics_driver';
    private const title = '物流驾驶员档案';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => '驾驶员编号',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'name' => [
                        'name'  => "姓名",
                        'width' => 100,
                    ],
                    'sex'  => [
                        'name'  => "性别",
                        'width' => 50,
                    ],
                    'idCard'  => [
                        'name'  => "身份证号",
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'contactTel'  => [
                        'name'  => "联系电话",
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'address'         => [
                        'name'  => '联系地址',
                        'width' => 200,
                    ],
                    'licenseNo'          => [
                        'name'  => '驾驶证号',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'firstDate'          => [
                        'name'  => '初次领证日期',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'startDate'          => [
                        'name'  => '驾驶证有效起始日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'endDate'          => [
                        'name'  => '驾驶证有效结束日期',
                        'width' => 180,
                        'sort' => 1,
                    ],
                    'level'          => [
                        'name'  => '准驾车型',
                        'width' => 100,
                        'sort' => 1,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "驾驶员编号" => text(array("name" => "orderNo")),
                    "姓名"   => text(array("name" => "name")),
                    "身份证号"   => text(array("name" => "idCard")),
                ],
                [
                    "联系电话"   => text(array("name" => "contactTel")),
                    '准驾车型' => select(array("name" => "level", "option" =>explode('，',para('driveType')))),
                    "有效结束日期" => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"newIframe('" . self::title . "详情','" . $url . "&fun=edit')\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//车辆编号
            "name" => $this->post('name'),//车牌号
            "idCard" => $this->post('idCard'),//车辆品牌
            "contactTel" => $this->post('contactTel'),//规格
        );
        //全等查询数组
        $equal = array(
            "level" => $this->post('level'),//类型
            'coid' => self::$coid
        );
        $and = "";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'),'date','endDate');
        }
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'endDate',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table, "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "edit" => array("title" => "编辑", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=edit&id=" . $array['id'] . "')"),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        $templateId = $this->get('templateId');
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        }   else {
            $exampleData[] = ['张三','男','500223199612144101','13000000000','重庆市','10000000000','2020-01-01','2020-01-01','2025-01-01','C1','样例数据，导入数据时请删除此行'];

            $excel    = $this->excelHead();
            $fileName = self::title.'导入模板-'.importTemplateClass::getName($templateId).'.xlsx';
            $filePath = $excel->fileName($fileName, 'sheet1');
            $format = new \Vtiful\Kernel\Format($filePath->getHandle());
            $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
            $index         = 0;
            foreach ($templateField as $k => $array) {
                if ($array['display']){
                    $backgroundStyle=null;
                    if (importTemplateClass::getIsMustValue($this->importFieldInit(), $array['columnName'])){
                        //必填项判断
                        $backgroundStyle  = $format->background(
                            0xFFC04B
                        )->toResource();
                    }
                    $filePath->insertText(0, $index, $array['aliasName'],'',$backgroundStyle);
                    foreach ($exampleData as $y=>$example){
                        $exampleVal = match ($array['columnName']){
                            '姓名'=>$example[0],
                            '性别'=>$example[1],
                            '身份证号'=>$example[2],
                            '联系电话'=>$example[3],
                            '地址'=>$example[4],
                            '驾驶证号'=>$example[5],
                            '初次领证日期'=>$example[6],
                            '驾驶证有效起始日期'=>$example[7],
                            '驾驶证有效结束日期'=>$example[8],
                            '准驾车型'=>$example[9],
                            '备注'=>$example[10],
                            default=>'',
                        };
                        $filePath->insertText($y+1, $index, $exampleVal);
                    }
                    $index++;
                }
            }

            $text   = $this->control['name'] . "下载了驾驶员档案导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOutPut($filePath,$fileName);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $templateId = $this->post('templateId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑的权限';
        }  else {
             $fomatArray = [];//导入数据格式同一为TYPE_STRING
            foreach ($this->importFieldInit() as $value){
                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
            }
            $data = $this->importHead(format: $fomatArray);
            $x = 0;
            $text = '';
            $headArray = [];
            $row_list=0;
            foreach ($data as $i => $row) {
                $row_list++;
                if ($i==0){
                    $templateField = importTemplateClass::templateField(self::page, 'importFieldInit', id:$templateId);
                    $headArray = importTemplateClass::combinHead($templateField,$row);
                }
                if ($i > 0) {
                    $rowData = formSubArray($row);
                    //只接收模板中选中的字段的值
                    $cell = [];
                    foreach ($headArray as $index=>$headName){
                        $cell[$headName] = $rowData[$index]??'';
                    }
                    //初始化未被模板需要的字段的值
                    foreach ($this->importFieldInit() as $value){
                        $cell[$value['columnName']] = $cell[$value['columnName']]??'';
                    }
                    $field = array(
                        "id" => self::getId(),
                        'coid' => self::$coid,
                        'stid'=>$this->control['stid'],
                        'name' => $cell['姓名'],
                        'sex' => $cell['性别'],
                        'idCard' => $cell['身份证号'],
                        'contactTel' => $cell['联系电话'],
                        'address' => $cell['地址'],
                        'licenseNo' =>$cell['驾驶证号'],
                        'firstDate' =>$cell['初次领证日期'],
                        'startDate' => $cell['驾驶证有效起始日期'],
                        'endDate' => $cell['驾驶证有效结束日期'],
                        'level' => $cell['准驾车型'],
                        'text' =>$cell['备注'],
                    );
                    $userNo = codeTemplateClass::generateCode(self::page,[
                        'prefix' => 'D',
                        'table' => self::table,
                        'field' => 'orderNo',
                        'where' => '',
                    ],$field);
                    $field['orderNo'] = $userNo;

                    $annotation = [
                        'name' => '姓名',
                        'sex' => '性别',
                        'idCard' => '身份证号',
                        'contactTel' => '联系电话',
                        'licenseNo' => '驾驶证号',
                        'firstDate' => '初次领证日期',
                        'startDate' => '驾驶证有效起始日期',
                        'endDate' => '驾驶证有效结束日期',
                        'level' => '准驾车型',
                    ];
                    $rules = [
                        'name' => 'required',
                        'sex' => 'required',
                        'idCard' => 'required|id_card',
                        'contactTel' => 'required|tel',
                        'licenseNo' => 'required',
                        'firstDate' => 'required|date',
                        'startDate' => 'required|date',
                        'endDate' => 'required|date',
                        'level' => 'required',
                    ];
                    // 校验是否符合规则
                    $vt = new \verify();
                    $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                    if($result === false){
                        $text.= "第【{$row_list}】行：".$vt->getErrs()[0]."<br>";  // 多个规则提示最前面一条
                    }elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and idCard ='$field[idCard]' and id !='$field[id]'")) >0){
                        $text.= "第【{$row_list}】行：已存在此身份证号的驾驶员<br>";
                    }else {
                        $warn = static::insert(["table" => self::table,"field" => $field]);
                        if (in_array($warn, ["新增成功", "更新成功"])) {
                            $x++;
                            $text .= "第【{$row_list}】行：导入成功<br>";
                        } else {
                            $text .= "第【{$row_list}】行：导入失败：编辑失败<br>";
                        }
                    }
                }
            }
            $total = count($data)-1;
            $json['data'] = [
                'text'=>$text,
                'title'=>"您导入了{$total}条数据，成功{$x}条，失败".($total-$x)."条",
            ];
            $text = $this->control['name'] . '导入了文件：'.$_FILES['file']['name'].'：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $json['warn'] = 2;
        }
        return json_encode($json,320);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => self::table,
                    "where" => "id in ('".implode("','", $checkedId)."') order by endDate desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '驾驶人编号'=>$array['orderNo'],
                            '姓名'=>$array['name'],
                            '性别'=>$array['sex'],
                            '身份证号'=>$array['idCard'],
                            '联系电话'=>$array['contactTel'],
                            '地址'=>$array['address'],
                            '驾驶证号'=>$array['licenseNo'],
                            '初次领证日期'=>$array['firstDate'],
                            '驾驶证有效起始日期'=>$array['startDate'],
                            '驾驶证有效结束日期'=>$array['endDate'],
                            '准驾车型'=>$array['level'],
                            '备注'=>$array['text'],
                            '创建人'=>self::findStaff($array['stid']),
                            '更新时间'=>$array['updateTime'],
                            '创建时间'=>$array['time'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了驾驶员档案";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "驾驶员档案.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));

    }

    /**
     * 编辑页
     * @return string
     */
    public function edit(): string
    {
        $id = $this->get('id') ?: self::getId();
        $info = query(self::table, " id = '" . $id . "' ");
        $button[] = [
            "name" => "保存",
            "type" => "点击事件",
            "fun" => "subForm('" . self::page . "EditForm,supplierImgSingleForm','" . root . "control/adIndex.html?cla=" . self::page . "&fun=editEdit')",
            'style' => 'li-btn-blue-bg',
        ];
        $licenseUrl = query('file',"targetId = '$id' and target ='身份证正面'");
        $licenseUrl2 = query('file',"targetId = '$id' and target ='身份证反面'");
        $licenseUr3 = query('file',"targetId = '$id' and target ='驾驶证'");
        $licenseUrl4 = query('file',"targetId = '$id' and target ='驾驶证副页'");
        $photo = array(
            array("title" => "身份证正面", 'type' => '身份证正面', 'fileId'=>$licenseUrl['id'] ?? '',"url" => $licenseUrl['src'] ?? '','id'=>$id),
            array("title" => "身份证反面", 'type' => '身份证反面', 'fileId'=>$licenseUrl['id'] ?? '',"url" => $licenseUrl2['src'] ?? '','id'=>$id),
            array("title" => "驾驶证", 'type' => '驾驶证', 'fileId'=>$licenseUrl['id'] ?? '',"url" => $licenseUr3['src'] ?? '','id'=>$id),
            array("title" => "驾驶证副页", 'type' => '驾驶证副页','fileId'=>$licenseUrl['id'] ?? '', "url" => $licenseUrl4['src'] ?? '','id'=>$id),
        );
        $talentObj = new talentPoolClass();
        //表单
        $data['button'] = $this->tableShowButton($button);
        $data['html'] = $this->pageEdit([
            "table" => [
                '基本信息' => [
                    [
                        must . "姓名：" =>  text(["name" => "name", 'class' => 'text', "value" => $info['name']]),
                        must . "性别：" => radio(array('name'=>'sex','value'=>['男','女'],'checked'=>$info['sex'])),
                        must . "身份证号：" => text(["name" => "idCard", 'class' => 'text', "value" => $info['idCard']]),
                        must . "联系电话：" => text(["name" => "contactTel", 'class' => 'text', "value" => $info['contactTel']]),
                    ],
                    [
                        "联系地址：" => text(["name" => "address", 'class' => 'text', "value" => $info['address']]),
                        must . "驾驶证号：" => text(["name" => "licenseNo", 'class' => 'text', "value" => $info['licenseNo']]),
                        must . "初次领证日期：" => text(["name" => "firstDate",'laydate' => [], "value" => $info['firstDate']]),
                        must . "驾驶证有效起始日期：" => text(["name" => "startDate",'laydate' => [], "value" => $info['startDate']]),
                    ],
                    [
                        must ."驾驶证有效结束日期：" => text(["name" => "endDate",'laydate' => [],"value" => $info['endDate']]),
                        must ."准驾车型：" => select(["name" => "level",'title'=>'准驾车型', 'option'=>explode('，',para('driveType')), "value" => $info['level']]),
                        "收款银行账号：" => text(["name" => "bankAccount", 'class' => 'text', "value" => $info['bankAccount']]),
                        "开户行：" => text(["name" => "bankName", 'class' => 'text', "value" => $info['bankName']]),
                    ],
                    [
                        "备注：" => textarea(["name" => "text",  'class' => 'textarea', "value" => $info['text']]),
                    ],
                ],
                '证件' => [
                    [$talentObj->photo($photo)],
                ]
            ],
            'hidden' => hidden(['name' => 'id', 'value' => $id]). "<div class='hidden'><input name=\"type\" type=\"hidden\" ><input name='imgFile' accept=\"image/*\" id='imgFile' type='file' onchange=\"uploadImgFile('{$this->get('cla')}EditForm',root+'control/adIndex.html?cla={$this->get('cla')}&fun=uploadIco')\"></div>",
        ]);
        $data['html'] .=  $this->editJs();

        //返回
        return $this->tab($data);
    }
    public function editJs()
    {
        $version = version;
        return <<<eof
<script>
     function delSingleIco(id){
      $.post(root+'control/adIndex.html?cla=talentPool&fun=delIco',{id:id},function(res) {
            if (res.warn ==2){
                $("[data-type='"+res.data.type+"']").attr('src',root+'img/images/emptyImg.jpg')
                 $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('src',root+'img/control/clickEdit.svg?v=$version');
                 $("[data-type='"+res.data.type+"']").closest('li').find(".edit-ico").attr('onclick',"clickUpload('"+res.data.type+"','"+res.data.id+"')")
            }else{
                msg(res.warn,'error')
            }
       },'json')
     }
</script>
eof;
    }
    /**
     *上传图片
     */
    function uploadIco()
    {
        $type = $this->post('type');
        $result = $this->saveFile($_FILES['imgFile'], self::page, explode(',', para('fileFormat')));
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        }elseif (empty($type)) {
            $json['warn'] = '未找到类型';
        }elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } elseif (!$result['code']) {
            $json['warn'] = $result['warn'];
        } else {
            $field = array(
                'src'=>$result['src'],
                'name'=>$result['fileName'],
                'size'=>$result['size'],
                'format'=>$result['suffix'],
            );
            $file = query('file',"targetId = '$id' and target = '$type'");
            if (empty($file['id'])){
                $field = array_merge($field,[
                    'id'=>self::getId(),
                    'stid'=>self::$stid,
                    'target'=>$type,
                    'targetId'=>$id,
                ]);
                $json['warn'] =static::insert(array(
                    'table'=>'file',
                    'field'=>$field
                ));
                $fileId = $field['id'];
            }else{
                $json['warn'] =static::update(array(
                    'table'=>'file',
                    'field'=>$field,
                    'where'=>"id = '$file[id]'"
                ));
                $fileId = $file['id'];
            }
            //添加日志
            if (in_array($json['warn'] ,['新增成功','更新成功'])) {
                fileDelete($file['src']);//删除之前的图片
                $json['warn'] = 2;
                $json['data']['src'] = root . $result['src'];
                $json['data']['id'] = $fileId;
                $json['data']['fileHtml'] = hidden(array('name'=>"imgId[]",'value'=>$fileId));
            }
        }
        return json_encode($json, 320);
    }
    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();

        $fileIdArr = $this->post('fileId');
        $field = [
            'name' => $this->post('name'),
            'sex' => $this->post('sex'),
            'idCard' => $this->post('idCard'),
            'contactTel' => $this->post('contactTel'),
            'address' => $this->post('address'),
            'licenseNo' => $this->post('licenseNo'),
            'firstDate' => $this->post('firstDate'),
            'startDate' => $this->post('startDate'),
            'endDate' => $this->post('endDate'),
            'level' => $this->post('level'),
            'bankAccount' => $this->post('bankAccount'),
            'bankName' => $this->post('bankName'),
            'text' => $this->post('text'),
        ];
        $annotation = [
            'name' => '姓名',
            'sex' => '性别',
            'idCard' => '身份证号',
            'contactTel' => '联系电话',
            'licenseNo' => '驾驶证号',
            'firstDate' => '初次领证日期',
            'startDate' => '驾驶证有效起始日期',
            'endDate' => '驾驶证有效结束日期',
            'level' => '准驾车型',
        ];
        $rules = [
            'name' => 'required',
            'sex' => 'required',
            'idCard' => 'required|id_card',
            'contactTel' => 'required|tel',
            'licenseNo' => 'required',
            'firstDate' => 'required',
            'startDate' => 'required',
            'endDate' => 'required',
            'level' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        }elseif(static::total(array('table'=>self::table,'where'=>"coid = '".self::$coid."' and idCard ='$field[idCard]' and id !='$id'")) >0){
            $json['warn'] = '已存在此身份证号的驾驶员';
        } elseif(strtotime($field['firstDate']) < strtotime($field['startDate'])){
            $json['warn'] =  "初次领证日期不能小于驾驶证有效开始日期";
        }elseif(strtotime($field['endDate']) < strtotime($field['startDate'])){
            $json['warn'] =  "驾驶证有效结束日期不能小于开始日期";
        }else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'D',
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $field = array_merge($field, [
                    'id' => $id,
                    'coid' => self::$coid,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'time' => $this->time
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //更新文件
                if (is_array($fileIdArr) && !static::isNull($fileIdArr)) {
                    update(['table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"]);
                }
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }

        resp:
        return json_encode($json, 320);
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "title" => self::title . '详情',
            );

            $button = [];
            if ($this->power(self::page, "edit")) {
                //按钮
                $button[] = [
                    "name" => "编辑",
                    "type" => "顶部页卡",
                    "title" => "编辑用户",
                    "url" => $this->root . "control/adIndex.html?cla={$this->get('cla')}&fun=edit&id=" . $info['id'],
                    'style' => 'li-btn-blue-bg',
                ];
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];

            }
            $licenseUrl = query('file',"targetId = '$info[id]' and target ='身份证正面'");
            $licenseUrl2 = query('file',"targetId = '$info[id]' and target ='身份证反面'");
            $licenseUr3 = query('file',"targetId = '$info[id]' and target ='驾驶证'");
            $licenseUrl4 = query('file',"targetId = '$info[id]' and target ='驾驶证副页'");
            $photo = array(
                array("title" => "身份证正面", 'type' => '身份证正面', 'cla'=>self::page,"url" => $licenseUrl['src']),
                array("title" => "身份证反面", 'type' => '身份证反面', 'cla'=>self::page,"url" => $licenseUrl2['src']),
                array("title" => "驾驶证", 'type' => '驾驶证', 'cla'=>self::page,"url" => $licenseUr3['src']),
                array("title" => "驾驶证副页", 'type' => '驾驶证副页','cla'=>self::page, "url" => $licenseUrl4['src']),
            );
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $data['html'] = $this->tableShow(array(
                '详细信息' => array(
                    array(
                        "姓名" => $info['name'],
                        "性别" => $info['sex'],
                        "身份证号" => $info['idCard'],
                        "联系电话" =>  $info['contactTel'],
                    ),
                    array(
                        "联系地址" => $info['address'],
                        "驾驶证号" => $info['licenseNo'],
                        "初次领证日期" => $info['firstDate'],
                        "驾驶证有效起始日期" => $info['startDate'],
                    ),
                    array(
                        "驾驶证有效结束日期" => $info['endDate'],
                        "准驾车型" => $info['level'],
                        "收款银行账号" => $info['bankAccount'],
                        "开户行" => $info['bankName'],
                    ),
                    array(

                        "备注" => pre($info['text']),
                    ),
                ),
                '系统信息' => array(
                    array(
                        "驾驶员编号" => $info['orderNo'],
                        "创建人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ),
                ),
                "证件" => [
                    [
                        supplierClass::singlePhoto($photo)
                    ]
                ]
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }
    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page. 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                update(array("table" => 'car','field'=>['driverId'=>''], "where" => " driverId = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;

                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }


    /**
     * 导入模板字段初始化
     * @return array[]
     */
    public function importFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'联系电话',
                    'aliasName'=>'联系电话',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                    'isMust'=>false,
                ],
                [
                    'columnName'=>'驾驶证号',
                    'aliasName'=>'驾驶证号',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'初次领证日期',
                    'aliasName'=>'初次领证日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'驾驶证有效起始日期',
                    'aliasName'=>'驾驶证有效起始日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'驾驶证有效结束日期',
                    'aliasName'=>'驾驶证有效结束日期',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'准驾车型',
                    'aliasName'=>'准驾车型',
                    'isMust'=>true,
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                    'isMust'=>false,
                ],
            ]
        };
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'驾驶人编号',
                    'aliasName'=>'驾驶人编号',
                ],
                [
                    'columnName'=>'姓名',
                    'aliasName'=>'姓名',
                ],
                [
                    'columnName'=>'性别',
                    'aliasName'=>'性别',
                ],
                [
                    'columnName'=>'身份证号',
                    'aliasName'=>'身份证号',
                ],
                [
                    'columnName'=>'联系电话',
                    'aliasName'=>'联系电话',
                ],
                [
                    'columnName'=>'地址',
                    'aliasName'=>'地址',
                ],
                [
                    'columnName'=>'驾驶证号',
                    'aliasName'=>'驾驶证号',
                ],
                [
                    'columnName'=>'初次领证日期',
                    'aliasName'=>'初次领证日期',
                ],
                [
                    'columnName'=>'驾驶证有效起始日期',
                    'aliasName'=>'驾驶证有效起始日期',
                ],
                [
                    'columnName'=>'驾驶证有效结束日期',
                    'aliasName'=>'驾驶证有效结束日期',
                ],
                [
                    'columnName'=>'准驾车型',
                    'aliasName'=>'准驾车型',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
                [
                    'columnName'=>'创建人',
                    'aliasName'=>'创建人',
                ],
                [
                    'columnName'=>'更新时间',
                    'aliasName'=>'更新时间',
                ],
                [
                    'columnName'=>'创建时间',
                    'aliasName'=>'创建时间',
                ],
            ]
        };
    }
}

